/* CustomerController.java
 *
 * Copyright (C) 2013 Universidad de Sevilla
 * 
 * The use of this project is hereby constrained to the conditions of the 
 * TDG Licence, a copy of which you may download from 
 * http://www.tdg-seville.info/License.html
 * 
 */

package controllers.customer;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import services.ActorService;
import services.BidService;
import controllers.AbstractController;
import domain.Bid;

@Controller
@RequestMapping("/bid/customer")
public class BidCustomerController extends AbstractController {

	//Services -----------------------------------------------------------------
	
	@Autowired
	BidService bidService;
	
	
	@Autowired
	ActorService actorService;
	// Constructors -----------------------------------------------------------

	public BidCustomerController() {
		super();
	}
	

	//Create and Edit
	// Creation ---------------------------------------------------------------

		@RequestMapping(value = "/create", method = RequestMethod.GET)
		public ModelAndView create(@RequestParam int auctionId) {
			ModelAndView result;
			

			Bid bid = bidService.create(auctionId);
			result = createEditModelAndView(bid);
		

			return result;
		}

		
		
	@RequestMapping(value = "/edit", method = RequestMethod.POST, params = "save")
	public ModelAndView save(@Valid Bid bid, BindingResult bindingResult) {
		ModelAndView result;		


		if (bindingResult.hasErrors()) {
			result = createEditModelAndView(bid);

		} else {
			try {
				
				bidService.save(bid);				
				result = new ModelAndView("redirect:/bid/actor/list.do");
				result.addObject("message", "bid.commit.success");
			} catch (Throwable oops) {
				result = createEditModelAndView(bid, oops.getMessage());
			}
		}

		return result;
	}


	// Ancillary methods ------------------------------------------------------

	protected ModelAndView createEditModelAndView(Bid bid) {
		ModelAndView result;

		result = createEditModelAndView(bid, null);

		return result;
	}

	protected ModelAndView createEditModelAndView(Bid bid, String message) {
		ModelAndView result;


		result = new ModelAndView("bid/edit");
		result.addObject("bid", bid);
		result.addObject("message", message);


		return result;
	}
	

	
}